package net.sudot.chess.business.controller.admin;

import net.sudot.chess.business.controller.AbstractBaseController;
import net.sudot.chess.business.model.User;
import net.sudot.chess.business.service.UserService;
import net.sudot.chess.config.SystemProperties;
import net.sudot.commons.security.Jwt;
import net.sudot.commons.security.JwtAuthenticationFilter;
import net.sudot.commons.security.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.SavedRequest;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 索引控制器
 *
 * @author tangjialin on 2018-03-21.
 */
@RestController("adminIndexController")
@RequestMapping(value = "/admin")
public class IndexController extends AbstractBaseController {
    @Resource
    private UserService userService;
    @Resource
    private SystemProperties systemProperties;
    @Resource
    private ServerProperties serverProperties;

    /**
     * 登录操作
     * <pre>
     *     用户未登录的情况下访问此接口,会被shiro拦截进入方法:{@link JwtAuthenticationFilter#executeLogin(javax.servlet.ServletRequest, javax.servlet.ServletResponse)}
     *     1.登录成功后{@link AuthenticatingFilter#onLoginSuccess(org.apache.shiro.authc.AuthenticationToken, org.apache.shiro.subject.Subject, javax.servlet.ServletRequest, javax.servlet.ServletResponse)}返回true会进入此方法
     *     2.用户已经登录的情况下调用此接口,则会进入此方法
     * </pre>
     *
     * @param user     登录用户信息
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @return 返回用户token等信息
     */
    @PostMapping("/login")
    public Object loginSuccess(@LoginUser User user, HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> data = new HashMap<>();
        SavedRequest savedRequest = org.apache.shiro.web.util.WebUtils.getAndClearSavedRequest(request);
        if (savedRequest != null && savedRequest.getMethod().equalsIgnoreCase(AccessControlFilter.GET_METHOD)) {
            data.put(HttpHeaders.LOCATION, savedRequest.getRequestUrl());
        }
        String authToken = request.getHeader(JwtAuthenticationFilter.USER_TOKEN_HEADER_NAME);
        if (authToken == null || authToken.isEmpty()) {
            if (user == null) {
                user = (User) SecurityUtils.getSubject().getPrincipal();
            }
            authToken = Jwt.create(new Jwt.Payload(user.getId().toString(), serverProperties.getServlet().getSession().getTimeout()), systemProperties.getJwtSecret());
        }
        data.put("token", authToken);
        return data;
    }

    /**
     * @param user
     * @return
     */
    @PostMapping("/logout")
    public ResponseEntity<Void> logout(@LoginUser User user) {
        userService.logout();
        return ResponseEntity.noContent().build();
    }
}
